#include "main.h"

// MF52 Temperature look up table
const double mf52[]={
483.8463,456.6244,431.1039,407.1685,384.7103,363.6294,343.8333,325.2361,307.7581,291.3257,   // -20 ~ -11
275.8701,261.3276,247.6390,234.7494,222.6075,211.1656,200.3796,190.2080,180.6125,171.5571,   // -10 ~ -1
163.0086,154.9356,147.3091,140.1019,133.2887,126.8458,120.7510,114.9837,109.5245,104.3552,   // 0 ~ 9
99.4589,94.8197,90.4228,86.2542,82.3008,78.5505,74.9916,71.6135,68.4060,65.3595,             // 10 ~ 19
62.4653,59.7148,57.1002,54.6141,52.2496,50.0000,47.8592,45.8214,43.8811,42.0331,             // 20 ~ 29
40.2726,38.5950,36.9961,35.4716,34.0179,32.6312,31.3081,30.0455,28.8402,27.6894,             // 30 ~ 39
26.5903,25.5404,24.5372,23.5785,22.6620,21.7857,20.9476,20.1459,19.3788,18.6448,             // 40 ~ 49
17.9421,17.2693,16.6251,16.0080,15.4167,14.8502,14.3072,13.7867,13.2876,12.8090,             // 50 ~ 59
12.3498,11.9093,11.4866,11.0809,10.6914,10.3174,9.9583,9.6133,9.2819,8.9634,                 // 60 ~ 69
8.6573,8.3631,8.0802,7.8082,7.5466,7.2950,7.0528,6.8198,6.5956,6.3797,                       // 70 ~ 79
6.1719,5.9717,5.7790,5.5933,5.4144,5.2420,5.0759,4.9158,4.7614,4.6125,                       // 80 ~ 89
4.4689,4.3305,4.1969,4.0680,3.9436,3.8236,3.7078,3.5959,3.4879,3.3836,                       // 90 ~ 99
3.2828,3.1855,3.0915,3.0007,2.9129,2.8280,2.7460,2.6666,2.5900,2.5158};                      // 100 ~ 109

void ADC_init()
{
	ADC_CR1 = 0x00;
	ADC_CR2 = 0x00;
	ADC_CSR = 0x02; //PC4 ,ain2
	ADC_TDRL = 0x01;
}

int get_ain()
{
	int result;
	ADC_CR1 = 0x01;
	delay(1);
	ADC_CR1 |= 0xFF&0x01;
	while((ADC_CSR&0x80)==0);
	result = (ADC_DRH<<2)+(ADC_DRL);
	return result;
}

double get_temp(){
	int adc_value, i;
	double res, temp;
	adc_value = get_ain();
	temp = ohm/10;
	res = (temp*adc_value)/(1023-adc_value);
	for(i=1;i<130;i++){
		if ((res<=mf52[i-1])&&(res>mf52[i])) {
			temp = i + (mf52[i-1]-res)/(mf52[i-1]-mf52[i]);
			break;
		}
	}
	return (temp - 20);
}